namespace Skymate.Mvc.Controllers.Dynamic.Scripting.Angular
{
    using System.Globalization;
    using System.Text;

    using Skymate.Extensions;
    using Skymate.Mvc;
    using Skymate.Mvc.Controllers.Dynamic;
    using Skymate.Mvc.Controllers.Dynamic.Scripting;

    internal class AngularActionScriptWriter
    {
        private readonly DynamicApiControllerInfo _controllerInfo;
        private readonly DynamicApiActionInfo _actionInfo;

        public AngularActionScriptWriter(DynamicApiControllerInfo controllerInfo, DynamicApiActionInfo methodInfo)
        {
            this._controllerInfo = controllerInfo;
            this._actionInfo = methodInfo;
        }

        public virtual void WriteTo(StringBuilder script)
        {
            script.AppendLine("                this." + this._actionInfo.ActionName.ToCamelCase() + " = function (" + ActionScriptingHelper.GenerateJsMethodParameterList(this._actionInfo.Method, "httpParams") + ") {");
            script.AppendLine("                    return $http(angular.extend({");
            script.AppendLine("                        abp: true,");
            script.AppendLine("                        url: '/" + ActionScriptingHelper.GenerateUrlWithParameters(this._controllerInfo, this._actionInfo) + "',");
            script.AppendLine("                        method: '" + this._actionInfo.Verb.ToString().ToUpper(CultureInfo.InvariantCulture) + "',");

            if (this._actionInfo.Verb == HttpVerb.Get)
            {
                script.AppendLine("                        params: " + ActionScriptingHelper.GenerateBody(this._actionInfo));
            }
            else
            {
                script.AppendLine("                        data: JSON.stringify(" + ActionScriptingHelper.GenerateBody(this._actionInfo) + ")");
            }

            script.AppendLine("                    }, httpParams));");
            script.AppendLine("                };");
            script.AppendLine("                ");
        }
    }
}